package com.fkdx.service;

import com.fkdx.common.dto.sys.CurrentUserDTO;
import com.fkdx.common.enums.SysStatusEnum;
import com.fkdx.common.enums.sys.GroupException;
import com.fkdx.common.sys.SecurityHelper;
import com.fkdx.dao.condition.TicalCondition;
import com.fkdx.dao.entity.PageResult;
import com.fkdx.dao.entity.Tical;
import com.fkdx.dao.entity.User;
import com.fkdx.dao.mapper.TicalMapper;
import com.fkdx.dao.mapper.UserMapper;
import com.fkdx.service.dto.DictQueryResp;
import com.fkdx.service.dto.TicalQueryReq;
import com.fkdx.service.dto.TicalQueryResp;
import com.fkdx.service.dto.TicalReq;
import com.google.common.collect.Lists;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: create by wsh
 * @date:2022/8/20
 */
@Log4j2
@Service()
public class TicalService {

  @Resource
  private TicalMapper ticalMapper;
  @Resource
  private TaskService taskService;
  @Resource
  private UserMapper userMapper;
  @Resource
  private DictService dictService;

  /**
   * 获取粮食品种集合     *     * @param req     * @return
   */
  public PageResult<TicalQueryResp> getTicalList(TicalQueryReq req) {
    CurrentUserDTO principal = SecurityHelper.getPrincipal();
    TicalCondition condition = new TicalCondition();
    BeanUtils.copyProperties(req, condition);
    condition.setTenantId(principal.getTenantId());
    if (principal.getIsCustom() == 0) {
      condition.setName(principal.getUserName());
    }
    List<Tical> list = ticalMapper.selectAll(condition);
    PageResult<TicalQueryResp> results = new PageResult<>(list, (m) -> {
      TicalQueryResp res = new TicalQueryResp();
      BeanUtils.copyProperties(m, res);
      return res;
    });
    return results;
  }

  /**
   * 获取详情     *     * @param id     * @return
   */
  public TicalQueryResp getTicalForm(Long id) {
    TicalQueryResp resp = new TicalQueryResp();
    Tical tical = ticalMapper.selectByPrimaryKey(id);
    BeanUtils.copyProperties(tical, resp);
    return resp;
  }

  /**
   * 新增、修改     *     * @param req
   */
  public void saveTicalForm(TicalReq req) {
    CurrentUserDTO principal = SecurityHelper.getPrincipal();
    Date d = new Date();
    if (req.getId() == null) {
      String[] urls = null;
      if (StringUtils.isNotEmpty(req.getUrl())) {
        urls = req.getUrl().split("http");
      }
      List<Tical> list = new ArrayList<>(urls.length);
      for (String s : urls) {
        if (StringUtils.isEmpty(s)) {
          continue;
        }
        Tical tical = new Tical();
        BeanUtils.copyProperties(req, tical);
        tical.setUrl("http".concat(s.trim()));
        tical.setStatus(2);
        tical.setCreated(d);
        tical.setModified(d);
        tical.setCreateUserId(principal.getId());
        tical.setCreateUserName(principal.getName());
        tical.setModificationUserId(principal.getId());
        tical.setModificationUserName(principal.getName());
        tical.setTenantId(principal.getTenantId());
        tical.setYn(SysStatusEnum.YES.getStatus());
        tical.setName(principal.getUserName());
        list.add(tical);
      }
      ticalMapper.insertBatch(list);
    } else {
      if (req.getStatus().equals(1)) {
        throw new GroupException("已执行不能修改");
      }
      Tical tical = new Tical();
      if (!req.getName().equals(principal.getUserName())) {
        throw new GroupException("非法请求");
      }
      if (StringUtils.isNotEmpty(req.getUrl())) {
        if (req.getUrl().split("http").length != 2){
          throw new GroupException("不能修改成多个链接");
        }
      }
      BeanUtils.copyProperties(req, tical);
      tical.setName(principal.getUserName());
      tical.setModificationUserId(principal.getId());
      tical.setModificationUserName(principal.getName());
      ticalMapper.updateByPrimaryKey(tical);
    }
  }

  /**
   * 删除     *     * @param id
   */
  public void removeTicalList(Long[] id) {
    ticalMapper.updateByIds(Lists.newArrayList(id));
  }

  public void confirm(TicalReq req) {
    CurrentUserDTO principal = SecurityHelper.getPrincipal();
    synchronized (principal.getId()) {
      List<Tical> l = ticalMapper.selectByType(principal.getUserName(), req.getType());
      if (l != null && !l.isEmpty()) {
        User user = userMapper.selecUserByUserName(principal.getUserName());
        DictQueryResp dict = dictService.getDictCode(req.getType().toString());
        int sum = 0;
        for (Tical t : l) {
          sum += t.getNum();
        }
        if (dict == null) {
          throw new GroupException("无法执行请联系管理员");
        }
        if (user.getIntegral() == null || user.getIntegral() <= 0) {
          throw new GroupException("积分不足");
        }
        Integer val = Integer.parseInt(dict.getDataCode()) * sum;
        if (user.getIntegral() < val) {
          throw new GroupException("该条操作积分不足");
        }
        for (Tical t : l) {
          Tical tical = new Tical();
          tical.setId(t.getId());
          tical.setStatus(0);
          tical.setName(principal.getUserName());
          tical.setModificationUserId(principal.getId());
          tical.setModificationUserName(principal.getName());
          ticalMapper.updateSelective(tical);
          taskService.saveBatch(t);
        }
      }
    }

/*
    Tical t = ticalMapper.selectByPrimaryKey(req.getId());
    User user = userMapper.selecUserByUserName(t.getName());
    DictQueryResp dict = dictService.getDictCode(t.getType().toString());
    if (dict == null) {
      throw new GroupException("无法执行请联系管理员");
    }
    if (user.getIntegral() == null || user.getIntegral() <= 0) {
      throw new GroupException("积分不足");
    }
    Integer val = Integer.parseInt(dict.getDataCode()) * t.getNum();

    if (user.getIntegral() < val) {
      throw new GroupException("该条操作积分不足");
    }

    Tical tical = new Tical();
    tical.setId(req.getId());
    tical.setStatus(0);
    tical.setName(principal.getUserName());
    tical.setModificationUserId(principal.getId());
    tical.setModificationUserName(principal.getName());
    ticalMapper.updateSelective(tical);
    User u = new User();
    u.setId(user.getId());
    u.setIntegral(user.getIntegral() - val);
    userMapper.updateSelective(u);
    taskService.saveBatch(t);*/

  }
}
